package customer.zspt.cn.customer.components.chat;
import android.Manifest;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.support.v4.view.ViewPager;
import android.text.Editable;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.style.ImageSpan;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.viewpagerindicator.CirclePageIndicator;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import customer.zspt.cn.customer.Adapter.ChatQuitePageAdapter;
import customer.zspt.cn.customer.Adapter.EnjoyAdapter;
import customer.zspt.cn.customer.Adapter.MoreVpAdapter;
import customer.zspt.cn.customer.R;
import customer.zspt.cn.customer.Widget.voice.AudioRecoderButton;
import customer.zspt.cn.customer.Widget.voice.AudioTimeTipView;
import customer.zspt.cn.customer.Widget.chat.ChatArticleMsgItem;
import customer.zspt.cn.customer.Widget.chat.ChatFileRightMsgItem;
import customer.zspt.cn.customer.Widget.chat.ChatMsgImage;
import customer.zspt.cn.customer.Widget.chat.ChatVocieMsgItem;
import customer.zspt.cn.customer.bean.ChatMsgDao;
import customer.zspt.cn.customer.bean.FriendInfoDao;
import customer.zspt.cn.customer.bean.GetChatMsgDao;
import customer.zspt.cn.customer.bean.GetGroupChatMsgDao;
import customer.zspt.cn.customer.bean.ImageUploadResultDao;
import customer.zspt.cn.customer.bean.LoginResultDao;
import customer.zspt.cn.customer.bean.QuiteArticletDao;
import customer.zspt.cn.customer.bean.QuiteFiletDao;
import customer.zspt.cn.customer.bean.QuiteOrderDao;
import customer.zspt.cn.customer.bean.QuiteTextDao;
import customer.zspt.cn.customer.bean.SendChatMsgDao;
import customer.zspt.cn.customer.bean.SkillInfoDao;
import customer.zspt.cn.customer.components.chat.ChatOrderContent.orderContentActivity;
import customer.zspt.cn.customer.components.chat.chatMore.ChildPager.ChatMoreChildPager;
import customer.zspt.cn.customer.components.chat.chatQuiteVp.BaseVpItem;
import customer.zspt.cn.customer.components.chat.chatQuiteVp.quiteArticleVpItem;
import customer.zspt.cn.customer.components.chat.chatQuiteVp.quiteFileVpItem;
import customer.zspt.cn.customer.components.chat.chatQuiteVp.quiteOrderVpItem;
import customer.zspt.cn.customer.components.chat.chatQuiteVp.quiteTextVpItem;
import customer.zspt.cn.customer.constant.chatMsgFieldName;
import customer.zspt.cn.customer.constant.constant;
import customer.zspt.cn.customer.sqlites.dao.chatMsgSqliteDao;
import customer.zspt.cn.customer.utils.ChatRecordSPUtils;
import customer.zspt.cn.customer.utils.Enjoy;
import customer.zspt.cn.customer.utils.MediaPlayUtils;
import customer.zspt.cn.customer.utils.NetUtils;
import customer.zspt.cn.customer.utils.RequestPermissionsUtils;
import customer.zspt.cn.customer.utils.SPUtils;
import customer.zspt.cn.customer.utils.SqlOptionsUtils;
import customer.zspt.cn.customer.utils.TimestampToBj;
import customer.zspt.cn.customer.utils.TvToEnjoy;
import customer.zspt.cn.customer.utils.WebScoket;
/*** Created by Administrator on 2018/7/6 0006.聊天界面*/
public class FriendChat extends Activity implements View.OnClickListener {
    //显示表情的gridview
    private static final int SHOWENJOYGV = 0;
    //显示更多
    private static final int SHOWENMORE = 1;
    //显示软键盘
    private static final int SHOWEDIT = 2;
    //分页查询
    private static final int ADDMOREMSG = 3;
    //我发送的消息
    private static final int MINESEND = 4;
    //我接收的消息
    private static final int MINEFROM = 5;
    //滚动到底部
    private static final int SCROLLBOTTOM = 6;
    /*** 录音提示*/


    @ViewInject(R.id.audioTip)
    AudioTimeTipView audioTip;
    String token;
    /*** 消息界面滑动事件监听*/
    int y = 0;
    View.OnTouchListener mChatOnTouchListener = new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    quite.setVisibility(View.GONE);
                    y = (int) event.getRawY();
                    break;
                case MotionEvent.ACTION_MOVE:
                    int moveY = (int) event.getRawY();
                    //向下滑动
                    if (moveY - y > 0) {
                        OnlyShowChatLL();
                        if (chat_sc.getScrollY() == 0) {
                            if(IsRefactorMsg){
                                if(look_more_tv.getVisibility()!=View.VISIBLE){
                                    if (HistoryMsgLoad_ll.getVisibility() == View.GONE){
                                        HistoryMsgLoad_ll.setVisibility(View.VISIBLE);
                                        mHandler.sendEmptyMessageDelayed(ADDMOREMSG, 1000);
                                    } else {
                                        return true;
                                    }
                                }
                            }
                        }
                    }
                    y = moveY;
                    break;
                case MotionEvent.ACTION_UP:
                    break;
            }
            return false;
        }
    };
    private GridView chat_gv;
    private ArrayList<ImageView> enjoy;
    private ArrayList<Bitmap> enjoy_rs = new ArrayList<>();
    private EditText input_contentET;
    private LinearLayout msgLv;
    private TvToEnjoy util;
    private Enjoy enjoyCs;
    //表情点击事件监听
    AdapterView.OnItemClickListener mOnEnjoyOnClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            Bitmap bitmap = enjoyCs.mBitmaps.get(i);
            int width = bitmap.getWidth();
            int height = bitmap.getHeight();
            Matrix matrix = new Matrix();
            matrix.postScale(2.7f, 2.7f);
            Bitmap mbitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
            BitmapDrawable face = new BitmapDrawable(mbitmap);
            addEnjoy(face, i);
        }
    };
    private List<Map<String, CharSequence>> msg_map = new ArrayList<>();
    private Button seng_msg;
    private EnjoyAdapter Edapter;
    private InputMethodManager mImm;
    private SendChatMsgDao msg;
    private BitmapUtils utils;
    @ViewInject(R.id.Media_ib)
    private ImageButton Media_ib;
    @ViewInject(R.id.record_button)
/*** 录音按钮*/
    private AudioRecoderButton record_button;
    private long ChatTime = 0;//聊天时间间隔
    private ImageView express_ib;
    private ImageView more;
    private String friendInfo;
    private LoginResultDao loginResultDao;
    private Gson gson;
    private FriendInfoDao.FriendInfo friendInfoDao;
    private SkillInfoDao.SkillInfo skillInfoDao;
    private GetChatMsgDao.getMsg touristInfoDao;
    private String touristInfo;
    /*** 游客的信息*/
    private String skillInfo;
    /*** 群聊的信息*/
    private String kefuId;//当前聊天的用户id
    private String history; //聊天人群
    private ScrollView chat_sc;
    private String type;
    private int MoreIcon[] = new int[]{R.drawable.camera, R.drawable.picture, R.drawable.quite, R.drawable.order_icon, R.drawable.move
            , R.drawable.ok, R.drawable.chat_history
            , R.drawable.card, R.drawable.local};//单聊
    private String MoreTitle[] = new String[]{"相机", "相册", "速回", "工单", "转移", "完成", "聊天记录", "名片", "位置"};
    private int GroupMoreIcon[] = new int[]{R.drawable.camera, R.drawable.picture,
            R.drawable.chat_history
            , R.drawable.card, R.drawable.local};//群聊
    private String GroupMoreTitle[] = new String[]{"相机", "相册", "聊天记录", "名片", "位置"};
    private List<Map<String, Object>> moreThing = new ArrayList<>();//更多功能的资料
    @ViewInject(R.id.bottom_item)
    private FrameLayout bottom_item;
    @ViewInject(R.id.more_vp) //更多功能
    private ViewPager more_vp;
    @ViewInject(R.id.indicator)
    private CirclePageIndicator indicator;
    @ViewInject(R.id.more_rl)
    private RelativeLayout more_rl;
    @ViewInject(R.id.quite)//速回
    private View quite;
    @ViewInject(R.id.quite_text)//标题
    private TextView quite_text;
    @ViewInject(R.id.quite_article)
    private TextView quite_article;
    @ViewInject(R.id.quite_file)
    private TextView quite_file;
    @ViewInject(R.id.quite_order)
    private TextView quite_order;
    @ViewInject(R.id.quite_showVP)
    private ViewPager quite_showVP;
    @ViewInject(R.id.article_line)
    private View article_line;//下划线
    @ViewInject(R.id.file_line)
    private View file_line;
    @ViewInject(R.id.text_line)
    private View text_line;
    @ViewInject(R.id.order_line)
    private View order_line;
    private ArrayList<BaseVpItem> VpData;
    /**
     * 速回vp滚动监听
     */
    ViewPager.OnPageChangeListener mQuiteVpScrollChangeListener = new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        }
        @Override
        public void onPageSelected(int position) {
            setLineState(position);
        }

        @Override
        public void onPageScrollStateChanged(int state) {
        }
    };
    @ViewInject(R.id.UserName)
    private TextView userName;//标题
    @ViewInject(R.id.back)//返回键
    private ImageView back;
    //文件的输出路径
    private File output;
    private Uri imageUri;
    //我的头像
    private String mineAvatar;
    //輸入框外層LinearLayout
    @ViewInject(R.id.edit_ll)
    private LinearLayout edit_ll;
    //加载的消息倍数
    private int msgCount = 0;
    //加载历史记录等待提示
    @ViewInject(R.id.HistoryMsgLoad_ll)
    private LinearLayout HistoryMsgLoad_ll;
    //录音状态监听
    AudioRecoderButton.OnAudioStatusUpdateListener mOnAudioStatusUpdateListener =
            new AudioRecoderButton.OnAudioStatusUpdateListener() {
                @Override
                public void onUpdate(double db, long time) {
                    audioTip.setVisibility(View.VISIBLE);
                    audioTip.setfileSize(db);
                }
                @Override
                public void onStop(String filePath, long time) {
                    audioTip.setVisibility(View.GONE);
                    setSendAudio(filePath, time);
                }
                @Override
                public void onShort() {
                    audioTip.OnShortTip();
                    /**隐藏提示框*/
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            audioTip.startRecording();
                            audioTip.setVisibility(View.GONE);
                        }
                    }, 200);
                }
                @Override
                public void cancel() {
                    audioTip.cancel();
                }

                @Override
                public void Recoding() {
                    audioTip.startRecording();
                }

                @Override
                public void OnGoneTip() {
                    audioTip.startRecording();
                    audioTip.setVisibility(View.GONE);
                }
            };
    private String historyMsg;
    //获取数据库对象
    private chatMsgSqliteDao msgSqliteDao;
    //添加聊天记录
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == SHOWENJOYGV) {
                setVoiceAEditAScrollView();
                setEnjoyShow();
            } else if (msg.what == SHOWENMORE) {
                setVoiceAEditAScrollView();
                setMoreShow();
            } else if (msg.what == SHOWEDIT) {
                OnlyShowChatLL();
                scrollToBottom();
            } else if (msg.what == ADDMOREMSG){
                int count = ++msgCount;
                if(count==3){
                    HistoryMsgLoad_ll.setVisibility(View.GONE);
                    look_more_tv.setVisibility(View.VISIBLE);
                    return;
                }
                addHistory(count);
            }else if(msg.what == SCROLLBOTTOM) {
                    scrollToBottom();
            }
            else {
                ChatMsgDao data = (ChatMsgDao) msg.obj;
                if (msg.arg1 == chatMsgFieldName.SEND) {
                    addMoreView(data, true, false);
                } else if (msg.arg1 == chatMsgFieldName.FROM) {
                    addMoreView(data, false, false);
                }
            }
        }
    };
    /**
     * 接收到新消息的事件监听
     */
    WebScoket.HsMsgListener mHsMsgListener = new WebScoket.HsMsgListener() {
        @Override
        public void success(String data) {
            pushMsg(data);
        }
    };
    //输入框内容改变监听器
    private TextWatcher mOnEidtTextChangeListener = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }
        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            if (TextUtils.isEmpty(charSequence)){
                seng_msg.setVisibility(View.GONE);
            } else {
                seng_msg.setVisibility(View.VISIBLE);
            }
        }
        @Override
        public void afterTextChanged(Editable editable) {
        }
    };
    //设置录音按钮，输入框和聊天界面滚动到底部
    private void setVoiceAEditAScrollView() {
        SOHAboutVoice(true);
        input_contentET.setFocusable(false);
        scrollToBottom();
    }
    //聊天记录
    @ViewInject(R.id.chat_history)
    private ImageView chat_history;
    //新增的聊天记录条数
    private int NewMsgCount = 0;
    @ViewInject(R.id.look_more_tv)
    private TextView look_more_tv;
    @Override
    protected void onCreate(Bundle savedInstanceState) throws NullPointerException {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.friendchat);
        ViewUtils.inject(this);
        look_more_tv.setVisibility(View.GONE);
        msgSqliteDao = chatMsgSqliteDao.getInstance(this);
        token = SPUtils.getString(this, "token", "");
        ChatTime = 0;
        history = ChatRecordSPUtils.getRecordString(this, constant.HISTROYCHATPEOPLE, constant.HISTROYCHATPEOPLE, "");
        utils = new BitmapUtils(this, constant.IMAGEPATH);
        type = getIntent().getStringExtra("type");
        if (type.equals("0")) {
            friendInfo = getIntent().getStringExtra("friendInfo");
        } else if (type.equals("1")) {
            skillInfo = getIntent().getStringExtra("skillInfoDao");
        } else if (type.equals("2")) {
            touristInfo = getIntent().getStringExtra("touristInfo");
        }
        initUI();
        setListener();
        initMoreItem();
    }
    //设置更多布局
    private void initMoreItem() {
        List<ChatMoreChildPager> pg = new ArrayList<>();
        int temp = 0;
        String MoreTitle[] = new String[]{};
        int MoreIcon[] = new int[]{};
        if (type.equals("0") || type.equals("2")) {
            MoreTitle = this.MoreTitle;
            MoreIcon = this.MoreIcon;
        } else {
            MoreTitle = this.GroupMoreTitle;
            MoreIcon = this.GroupMoreIcon;
        }
        for (int i = 0; i < MoreTitle.length; i++) {
            temp++;
            Map<String, Object> map = new HashMap<>();
            map.put("title", MoreTitle[i]);
            map.put("icon", MoreIcon[i]);
            moreThing.add(map);
            if (temp == 8) {
                temp = 0;
                ChatMoreChildPager pager = new ChatMoreChildPager(this, moreThing);
                pg.add(pager);
                moreThing.removeAll(moreThing);
            }
        }
        if (moreThing.size() > 0) {
            ChatMoreChildPager pager = new ChatMoreChildPager(this, moreThing);
            moreThing.removeAll(moreThing);
            pg.add(pager);
        }
        MoreVpAdapter adapter = new MoreVpAdapter(pg);
        more_vp.setAdapter(adapter);
        indicator.setViewPager(more_vp);
        indicator.onPageSelected(0);
        indicator.setSnap(true);
        adapter.getItemTitle(new MoreVpAdapter.getTitleLintener() {
            @Override
            public void getMoreItemTitle(String title) {
                Log.e("title", title);
                ChooseFunction(title);
            }
        });
    }
    /*** 通过name开启相应的功能 @param title*/
    private void ChooseFunction(String title) {
        switch (title) {
            case "相机":
                if (RequestPermissionsUtils.checkCameraPermission(this)) {
                    takePhoto();
                }
                break;
            case "相册":
                //打开相册,检查存储權限
                if (RequestPermissionsUtils.checkRWritePermission(this)) {
                    OpenChooseImage();
                }
                break;
            case "速回":
                quite.setVisibility(View.VISIBLE);
                quite_showVP.setCurrentItem(0);
                setLineState(0);
                break;
            case "工单":
                Intent intent = new Intent(this, orderContentActivity.class);
                intent.putExtra("User", loginResultDao.data.realname);
                startActivityForResult(intent, 200);
                break;
            case "转移":
                break;
            case "完成":
                break;
            case "聊天记录":
                break;
            case "名片":
                break;
            case "位置":
                break;
        }
    }
    /*** 显示更多*/
    public void setMoreShow() {
        bottom_item.setVisibility(View.VISIBLE);
        chat_gv.setVisibility(View.GONE);
        more_rl.setVisibility(View.VISIBLE);
    }
    /*** 显示表情*/
    public void setEnjoyShow() {
        bottom_item.setVisibility(View.VISIBLE);
        more_rl.setVisibility(View.GONE);
        chat_gv.setVisibility(View.VISIBLE);
    }
    //是否刷新历史聊天记录
    boolean IsRefactorMsg = true;
    //添加历史记录
    private void addHistory(int MsgCount) {
        //获取查询的消息集合
        List<ChatMsgDao> queryList = msgSqliteDao.query(kefuId,
                constant.queryMsgCount * MsgCount + NewMsgCount,
                constant.queryMsgCount * (MsgCount + 1)+NewMsgCount);
        if (queryList.size() == 0) {
            //是否到顶了
            IsRefactorMsg = false;
            HistoryMsgLoad_ll.setVisibility(View.GONE);
            return;
        }
        for (ChatMsgDao dao : queryList) {
            //发来的消息
            if (dao.getSendOrfrom() == chatMsgFieldName.FROM) {
                addMoreView(dao, false, true);
            } else if (dao.getSendOrfrom() == chatMsgFieldName.SEND) {
                addMoreView(dao, true, true);
            }
        }
        if(MsgCount == 0){
            mHandler.sendEmptyMessageDelayed(SCROLLBOTTOM,300);
        }
        HistoryMsgLoad_ll.setVisibility(View.GONE);
    }
    //判断是否是我发出的
    private void addMoreView(ChatMsgDao dao, boolean isMine, boolean flashback) {
        int MsgType = dao.getMsgType();
        if (isMine) {
            addMineView(MsgType, dao, flashback,false);
        } else {
            addMineView(MsgType, dao, flashback,true);
        }
    }
    private void addFromTextMsg(ChatMsgDao dao, boolean flashback) {
        View view = View.inflate(this, R.layout.chat_msg_ts_right_item, null);
        //消息内容
        TextView Tv_msgContent = (TextView) view.findViewById(R.id.Tv_msgContent);
        TextView msg_time = (TextView) view.findViewById(R.id.msg_time);
        CharSequence charSequence = solveData(dao.getChatContent());
        CharSequence replace = util.replace(charSequence);
        Tv_msgContent.setText(replace);
        //消息内容
        ImageView userIg = (ImageView) view.findViewById(R.id.header_portrait);
        if (dao.getTempTime() - ChatTime > 3 * 60 * 1000) {
            msg_time.setText(TimestampToBj.getBeijingTime(dao.getTempTime()));
        } else {
            msg_time.setVisibility(View.GONE);
        }
        ChatTime = dao.getTempTime();
        utils.display(userIg, dao.getAvater());
        if (flashback) {
            msgLv.addView(view, 1);
        } else {
            msgLv.addView(view);
            scrollToBottom();
        }
    }
    //我
    public void addMineView(int type, ChatMsgDao dao, boolean flashback,boolean isLeft) {
        String[] split = dao.getChatContent().split("\\[");
        String IW = null;
        switch (type) {
            //图片
            case chatMsgFieldName.IMAGE:
                //添加图片消息
                addMineImageMsg(dao, flashback, split,isLeft);
                break;
            //音频
            case chatMsgFieldName.VOICE:
                //添加语音消息
                addMineVocieMsg(dao, flashback, split,isLeft);
                break;
            //视频
            case chatMsgFieldName.VIDEO:
                break;
            //文件
            case chatMsgFieldName.FILE:
                //添加文件消息
                addMineFileMsg(dao, flashback, split,isLeft);
                break;
            //文章
            case chatMsgFieldName.ESSAY:
                //添加文章消息
                addMineArticleMsg(dao, flashback, split,isLeft);
                break;
            //聊天
            default:
                //添加文本消息
                if(isLeft){
                    addFromTextMsg(dao,flashback);
                }else{
                    addMineTextMsg(dao, flashback);
                }
                //消息内容
                break;
        }
    }
    private void addMineTextMsg(ChatMsgDao dao, boolean flashback) {
        //如果是我发送的
        View view = View.inflate(this, R.layout.chat_msg_ts_left_item, null);
        //消息内容
        TextView Tv_msgContent = (TextView) view.findViewById(R.id.Tv_msgContent);
        TextView msg_time = (TextView) view.findViewById(R.id.msg_time);
        CharSequence charSequence = solveData(dao.getChatContent());
        CharSequence replace = util.replace(charSequence);
        Tv_msgContent.setText(replace);
        ImageView userIg = (ImageView) view.findViewById(R.id.header_portrait);
        if (dao.getTempTime() - ChatTime > 3 * 60 * 1000) {
            msg_time.setText(TimestampToBj.getBeijingTime(dao.getTempTime()));
        } else {
            msg_time.setVisibility(View.GONE);
        }
        utils.display(userIg, dao.getAvater());
        if (flashback) {
            msgLv.addView(view, 1);
        } else {
            msgLv.addView(view);
            scrollToBottom();
        }
        ChatTime = dao.getTempTime();
    }
    private void addMineImageMsg(ChatMsgDao dao, boolean flashback, String[] split,boolean isLeft) {
        String IW;
        IW = split[1].replaceAll("\\]", "");
        ChatMsgImage chatMsgMineImage = new ChatMsgImage(this,isLeft);
        chatMsgMineImage.setHeader_portrait(dao.getAvater());
        chatMsgMineImage.setMsg_img(IW);
        chatMsgMineImage.setTime(dao.getTempTime(), ChatTime);
        if (flashback) {
            msgLv.addView(chatMsgMineImage, 1);
        } else {
            msgLv.addView(chatMsgMineImage);
            scrollToBottom();
        }
        ChatTime = dao.getTempTime();
    }
    private void addMineVocieMsg(ChatMsgDao dao, boolean flashback, String[] split,boolean isLeft) {
        String IW;
        IW = split[1].replaceAll("\\]", "");
        String content[] = IW.split("\\|");
        ChatVocieMsgItem rightMsgItem = new ChatVocieMsgItem(this,isLeft);
        rightMsgItem.audioTime(content[1]);
        rightMsgItem.setHttpAudio(content[0]);
        rightMsgItem.setTime(dao.getTempTime(), ChatTime);
        rightMsgItem.setAvater(dao.getAvater());
        ChatTime = dao.getTempTime();
        if (flashback) {
            msgLv.addView(rightMsgItem, 1);
        } else {
            msgLv.addView(rightMsgItem);
            scrollToBottom();
        }
    }

    private void addMineFileMsg(ChatMsgDao dao, boolean flashback, String[] split,boolean isLeft) {
        String IW;
        IW = split[1].replaceAll("\\]", "");
        String[] fileBasic = IW.split("\\|");
        ChatFileRightMsgItem fileRightMsgItem = new ChatFileRightMsgItem(this,isLeft);
        fileRightMsgItem.setHeader_portrait(dao.getAvater());
        fileRightMsgItem.setTime(dao.getTempTime(), ChatTime);
        fileRightMsgItem.setfileUrl(fileBasic[0]);
        fileRightMsgItem.setFileTitle(fileBasic[1]);
        fileRightMsgItem.setFile_Size(fileBasic[2]);
        if (flashback) {
            msgLv.addView(fileRightMsgItem, 1);
        } else {
            msgLv.addView(fileRightMsgItem);
            scrollToBottom();
        }
        ChatTime = dao.getTempTime();
    }

    private void addMineArticleMsg(ChatMsgDao dao, boolean flashback, String[] split,boolean isLeft) {
        String IW;
        IW = split[1].replaceAll("\\]", "");
        String[] essayBasic = IW.split("\\|");
        ChatArticleMsgItem articleRightMsgItem = new ChatArticleMsgItem(this,isLeft);
        articleRightMsgItem.setArticleUrl(essayBasic[0]);
        articleRightMsgItem.setArticle_ig(essayBasic[1]);
        articleRightMsgItem.setArticleTitle(essayBasic[2]);
        articleRightMsgItem.setArticle_outline(essayBasic[3]);
        articleRightMsgItem.setHeader_portrait(dao.getAvater());
        articleRightMsgItem.setTime(dao.getTempTime(), ChatTime);
        if (flashback) {
            msgLv.addView(articleRightMsgItem, 1);
        } else {
            msgLv.addView(articleRightMsgItem);
            scrollToBottom();
        }
        ChatTime = dao.getTempTime();
    }
    private void scrollToBottom() {
        new Handler().post(new Runnable() {
            @Override
            public void run() {
                HistoryMsgLoad_ll.setVisibility(View.GONE);
                chat_sc.fullScroll(ScrollView.FOCUS_DOWN);
            }
        });
    }
    //將消息轉意
    private void addInfo(String content, int Msgtype) {
        msg = new SendChatMsgDao();
        SendChatMsgDao.chatmsg chat = msg.new chatmsg();
        SendChatMsgDao.From from = msg.new From();
        SendChatMsgDao.To to = msg.new To();
        msg.data = chat;
        msg.data.mine = from;
        msg.data.to = to;
        msg.data.mine.cid = getCid();
        msg.data.mine.avatar = loginResultDao.data.avatar;
        msg.data.mine.id = "companyid_" + loginResultDao.data.companyid + "_usertype_"
                + loginResultDao.data.usertype + "_user_" + loginResultDao.data.userid;
        msg.data.mine.mine = true;
        msg.data.mine.name = loginResultDao.data.realname;
        msg.data.mine.timestamp = System.currentTimeMillis();
        msg.data.mine.username = loginResultDao.data.nickname;
        msg.data.mine.content = content;
        //聯係人
        msg.data.to.timestamp = System.currentTimeMillis();
        if (type.equals("0")) {
            msg.data.to.avatar = friendInfoDao.kefuAvatar;
            msg.data.to.name = friendInfoDao.kefuRealname + "[" + friendInfoDao.kefuNickname + "]";
            msg.data.to.usertype = "kefu";
            msg.data.to.id = "companyid_" + friendInfoDao.companyid + "_usertype_kefu"
                    + "_user_" + friendInfoDao.kefuId;
            msg.data.to.username = friendInfoDao.kefuNickname;
        } else if (type.equals("1")) {
            msg.data.to.avatar = "http://im.oss.yomiyun.com/group.png";
            msg.data.to.name = skillInfoDao.skillTitle;
            msg.data.to.usertype = "group";
            msg.data.to.id = "companyid_" + skillInfoDao.companyid + "_grouptype_kefu"
                    + "_group_" + skillInfoDao.skillId;
        } else if (type.equals("2")) {
            msg.data.to.avatar = "http://uc.oss.yomiyun.com/avatar.png";
            msg.data.to.name = touristInfoDao.name;
            msg.data.to.usertype = "tourist";
            msg.data.to.id = touristInfoDao.fromid;
        }
        msg.data.to.type = type.equals("1") ? "group" : "friend";
        msg.type = "chatMessage";
        String s = gson.toJson(msg);
        try {
            WebScoket.webSocketClient.send(s);
            //向表中添加数据
            String avater = msg.data.mine.avatar;
            long time = System.currentTimeMillis();
            String userName = msg.data.mine.name;
            String groupAvater = "", groupName = "", chatobjavater = "", chatobjname = "";
            if (skillInfoDao != null) {
                groupAvater = msg.data.to.avatar;
                groupName = msg.data.to.name;
            } else if (friendInfoDao != null) {
                chatobjavater = friendInfoDao.kefuAvatar;
                chatobjname = friendInfoDao.kefuRealname;
            } else if (touristInfoDao != null) {
                chatobjavater = touristInfoDao.avatar;
                chatobjname = touristInfoDao.name;
            }
            //增加聊天记录
            String sql;
            String dateTime = TimestampToBj.getTime(time);
            sql = SqlOptionsUtils.SqlStr(kefuId, avater, content,
                    chatMsgFieldName.SEND, time, userName,
                    chatMsgFieldName.READ, Msgtype, groupAvater, groupName, chatobjavater, chatobjname,dateTime);
            msgSqliteDao.Update(sql);
            if (!history.contains(kefuId)) {
                history += kefuId + ",";
                ChatRecordSPUtils.setRecordString(this, constant.HISTROYCHATPEOPLE, constant.HISTROYCHATPEOPLE, history);
            }
            //发送消息更新界面-->如果是需要上传文件的则不再需要更新界面
            if (Msgtype == chatMsgFieldName.CONTENT) {
                ChatMsgDao dao = SqlOptionsUtils.getChatMsgDao(avater, content, chatMsgFieldName.SEND
                        , time, userName, chatMsgFieldName.READ, chatMsgFieldName.CONTENT);
                Message msgHd = new Message();
                msgHd.obj = dao;
                msgHd.arg1 = chatMsgFieldName.SEND;
                msgHd.what = MINESEND;
                mHandler.sendMessage(msgHd);
            }
        } catch (Exception e) {
            e.printStackTrace();
            if (NetUtils.getNetWorkState(this) == NetUtils.NOTNET) {
                Toast.makeText(this, "发送失败,可能是网络异常,该条消息将不会保留", Toast.LENGTH_SHORT).show();
            }
        }
    }
    //获取uuid
    public String getCid() {
        return UUID.randomUUID().toString();
    }

    public void initUI() throws NullPointerException {
        //軟件盤
        mImm = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
        String info = SPUtils.getString(this, constant.LOGINRESULT, "");
        gson = new Gson();
        loginResultDao = gson.fromJson(info, LoginResultDao.class);
        /**我的头像*/
        mineAvatar = loginResultDao.data.avatar;
        if (type.equals("0")) {
            //朋友
            friendInfoDao = gson.fromJson(friendInfo, FriendInfoDao.FriendInfo.class);
            kefuId = "companyid_" + friendInfoDao.companyid + "_usertype_kefu"
                    + "_user_" + friendInfoDao.kefuId;
            userName.setText(friendInfoDao.kefuRealname + "[" + friendInfoDao.kefuNickname + "]");
        } else if (type.equals("1")) {
            //群聊
            skillInfoDao = gson.fromJson(skillInfo, SkillInfoDao.SkillInfo.class);
            kefuId = "companyid_" + skillInfoDao.companyid + "_grouptype_kefu"
                    + "_group_" + skillInfoDao.skillId;
            userName.setText(skillInfoDao.skillTitle);
        } else if (type.equals("2")) {
            touristInfoDao = gson.fromJson(touristInfo, GetChatMsgDao.getMsg.class);
            kefuId = touristInfoDao.fromid;
            userName.setText(touristInfoDao.name);
        }
        //创建聊天表
        msgSqliteDao.addNewTable(kefuId, "");
        ChatRecordSPUtils.setRecordString(this, kefuId, kefuId + "_count", "0");
        chat_gv = (GridView) findViewById(R.id.enjoy_Gv);
        chat_sc = (ScrollView) findViewById(R.id.chat_sc);
        msgLv = (LinearLayout) findViewById(R.id.msg);
        enjoy = new ArrayList<>();
        input_contentET = findViewById(R.id.input_contentET);
        enjoyCs = new Enjoy(this);
        util = new TvToEnjoy(this);
        input_contentET = findViewById(R.id.input_contentET);
        for (int i = 0; i < enjoyCs.mBitmaps.size(); i++) {
            ImageView ig = new ImageView(this);
            ig.setImageBitmap(enjoyCs.mBitmaps.get(i));
            enjoy.add(ig);
        }
        Edapter = new EnjoyAdapter(enjoy);
        chat_gv.setAdapter(Edapter);
        seng_msg = (Button) findViewById(R.id.seng_msg);
        express_ib = (ImageView) findViewById(R.id.express_ib);
        more = (ImageView) findViewById(R.id.more);
        //初始化聊天记录
        addHistory(msgCount);
    }

    /*** 设置监听事件*/
    public void setListener() {
        Media_ib.setOnClickListener(this);
        record_button.setOnClickListener(this);
        express_ib.setOnClickListener(this);
        input_contentET.setOnClickListener(this);
        seng_msg.setOnClickListener(this);
        more.setOnClickListener(this);
        quite_text.setOnClickListener(this);
        quite_article.setOnClickListener(this);
        quite_file.setOnClickListener(this);
        quite_order.setOnClickListener(this);
        back.setOnClickListener(this);
        chat_history.setOnClickListener(this);
        input_contentET.addTextChangedListener(mOnEidtTextChangeListener);
        /**表情的点击事件*/
        chat_gv.setOnItemClickListener(mOnEnjoyOnClickListener);
        /**设置速回的数据*/
        setQuiteItemData();
        //速回vp选中事件
        quite_showVP.setOnPageChangeListener(mQuiteVpScrollChangeListener);
        /**录音状态的监听*/
        record_button.getAudioStatusInfoLinstener(mOnAudioStatusUpdateListener);
        final Handler handler = new Handler();
        chat_sc.setOnTouchListener(mChatOnTouchListener);
        /**消息的监听*/
        WebScoket.HsMsgChangeListener(mHsMsgListener);
    }
    /**
     * 只显示聊天界面与输入框
     */
    private void OnlyShowChatLL() {
        mImm.hideSoftInputFromWindow(input_contentET.getWindowToken(), 0);
        bottom_item.setVisibility(View.GONE);
        quite.setVisibility(View.GONE);
    }
    public void setQuiteItemData() {
        VpData = new ArrayList<>();
        VpData.add(new quiteTextVpItem(this));
        VpData.add(new quiteArticleVpItem(this));
        VpData.add(new quiteFileVpItem(this));
        VpData.add(new quiteOrderVpItem(this));
        ChatQuitePageAdapter adapter = new ChatQuitePageAdapter(VpData, this);
        quite_showVP.setAdapter(adapter);
        VpData.get(0).initData();
        //数据点击
        adapter.getBasicItemDataLintener(new ChatQuitePageAdapter.BasicItemDataLintener() {
            @Override
            public void getData(Object data) {
                setMSg(data);
            }
        });
    }
    /*** 选择点击的条目及类型*/
    public void setMSg(Object data) {
        //文章
        if (data instanceof QuiteArticletDao.Article) {
            QuiteArticletDao.Article Letter = (QuiteArticletDao.Article) data;
            String content = "essay[" + Letter.articleUrl + "|" + Letter.articleImgurl + "|" +
                    Letter.articleTitle + "|" + Letter.articleRemark + "]";
            addInfo(content, 0);
        }
        //文本
        else if (data instanceof QuiteTextDao.TextDao) {
            QuiteTextDao.TextDao Letter = (QuiteTextDao.TextDao) data;
            addInfo(Letter.textTitle, 0);
        }
        //文件
        else if (data instanceof QuiteFiletDao.FileDao) {
            QuiteFiletDao.FileDao Letter = (QuiteFiletDao.FileDao) data;
            String content = "file[" + Letter.filexPath + "|" + Letter.filexTitle + "|" +
                    Letter.filexSize + "]";
            addInfo(content, 0);
        }
        //表单
        else if (data instanceof QuiteOrderDao.OrderDao) {
            QuiteOrderDao.OrderDao Letter = (QuiteOrderDao.OrderDao) data;
        }
        quite.setVisibility(View.GONE);
    }

    /**
     * 设置速回的选择事件
     */
    private void setLineState(int position) {
        quite_text.setSelected(position == 0);
        quite_article.setSelected(position == 1);
        quite_file.setSelected(position == 2);
        quite_order.setSelected(position == 3);
        text_line.setVisibility(position == 0 ? View.VISIBLE : View.GONE);
        article_line.setVisibility(position == 1 ? View.VISIBLE : View.GONE);
        file_line.setVisibility(position == 2 ? View.VISIBLE : View.GONE);
        order_line.setVisibility(position == 3 ? View.VISIBLE : View.GONE);
        quite_showVP.setCurrentItem(position);
        VpData.get(position).initData();
    }
    //將字符轉化成表情
    public void addEnjoy(Drawable drawable, int index) {
        SpannableString spannableString = new SpannableString(enjoyCs.mEnjoyList[index]);
        drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
        ImageSpan span = new ImageSpan(drawable, ImageSpan.ALIGN_BOTTOM);
        spannableString.setSpan(span, 0, enjoyCs.mEnjoyList[index].length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        int currentPosition = input_contentET.getSelectionStart();//得到当前光标位置
        input_contentET.getText().insert(currentPosition, spannableString);//插入表情
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            /**表情*/
            case R.id.express_ib:
                mImm.hideSoftInputFromWindow(input_contentET.getWindowToken(), 0);
                mHandler.sendEmptyMessageDelayed(SHOWENJOYGV, 200);
                break;
            case R.id.input_contentET:
                mHandler.sendEmptyMessageDelayed(SHOWEDIT, 100);
                break;
            /**发送按钮*/
            case R.id.seng_msg:
                String msgTv = input_contentET.getText().toString();
                input_contentET.setText("");
                pickData(msgTv.toString());
                if(bottom_item.getVisibility()==View.GONE){
                    mHandler.sendEmptyMessageDelayed(SHOWEDIT, 100);
                }
                break;
            case R.id.more:
                mImm.hideSoftInputFromWindow(input_contentET.getWindowToken(), 0);
                mHandler.sendEmptyMessageDelayed(SHOWENMORE, 200);
                break;
            case R.id.quite_text:
                setLineState(0);
                break;
            case R.id.quite_article:
                setLineState(1);
                break;
            case R.id.quite_file:
                setLineState(2);
                break;
            case R.id.quite_order:
                setLineState(3);
                break;
            case R.id.back:
                finish();
                break;
            /**点击录音按钮*/
            case R.id.Media_ib:
                //申请权限
                if (edit_ll.getVisibility() != View.GONE) {
                    RequestPermissionsUtils.checkAudioRecordPermission(this);
                    SOHAboutVoice(false);
                    mImm.hideSoftInputFromWindow(input_contentET.getWindowToken(), 0);
                    bottom_item.setVisibility(View.GONE);
                } else {
                    SOHAboutVoice(true);
                    bottom_item.setVisibility(View.GONE);
                    mImm.showSoftInput(input_contentET, 0);
                }
                break;
            case R.id.chat_history:
                Intent intent = new Intent();
                intent.setClass(this,ChatHistory.class);
                intent.putExtra("kefuId",kefuId);
                startActivity(intent);
                 break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ChatRecordSPUtils.setRecordString(this, kefuId, kefuId + "_count", "0");
    }
    //顯示或隱藏錄音按鈕
    private void SOHAboutVoice(boolean flag) {
        if (flag) {
            Media_ib.setImageResource(R.drawable.media);
            edit_ll.setVisibility(View.VISIBLE);
        } else {
            edit_ll.setVisibility(View.GONE);
            Media_ib.setImageResource(R.drawable.keybored);
        }
    }

    //文字转化成消息格式
    private void pickData(String msg) {
        for (int i = 0; i < enjoyCs.mEnjoyList.length; i++) {
            msg = msg.replace(enjoyCs.mEnjoyList[i], "face" + enjoyCs.mEnjoyList[i]);
        }
        /**0文字表情*/
        addInfo(msg, 0);
    }
    //解析聊天记录
    private void pushMsg(String data) {
        String chatId = "";
        ChatMsgDao dao = new ChatMsgDao();
        boolean isGroup = false;
        if (data.contains("groupname") && data.contains("groupavatar")) {
            GetGroupChatMsgDao getgroupChatMsgDao = gson.fromJson(data, GetGroupChatMsgDao.class);
            chatId = getgroupChatMsgDao.data.id;
            //添加聊天成员
            if (!history.contains(getgroupChatMsgDao.data.id)) {
                history += getgroupChatMsgDao.data.id + ",";
                ChatRecordSPUtils.setRecordString(this, constant.HISTROYCHATPEOPLE, constant.HISTROYCHATPEOPLE, history);
            }
            isGroup = true;
        } else if (data.contains("usertype_kefu")) {
            GetChatMsgDao getChatMsgDao = gson.fromJson(data, GetChatMsgDao.class);
            chatId = getChatMsgDao.data.id;
            //添加聊天成员
            if (!history.contains(getChatMsgDao.data.id)) {
                history += getChatMsgDao.data.id + ",";
                ChatRecordSPUtils.setRecordString(this, constant.HISTROYCHATPEOPLE, constant.HISTROYCHATPEOPLE, history);
            }
            isGroup = false;
        } else if (data.contains("usertype_tourist")) {
            GetChatMsgDao getChatMsgDao = gson.fromJson(data, GetChatMsgDao.class);
            chatId = getChatMsgDao.data.id;
            //添加聊天成员
            if (!history.contains(getChatMsgDao.data.id)) {
                history += getChatMsgDao.data.id + ",";
                ChatRecordSPUtils.setRecordString(this, constant.HISTROYCHATPEOPLE, constant.HISTROYCHATPEOPLE, history);
            }
            isGroup = false;
        }
        //如果单聊的消息
        if (chatId.equals(kefuId) && !type.equals("1")) {
            Message msg = new Message();
            msg.obj = dateToDao(data);
            msg.what = MINEFROM;
            msg.arg1 = chatMsgFieldName.FROM;
            mHandler.sendMessage(msg);
        }
        //如果是群聊的消息
        if (isGroup && type.equals("1")) {
            Message msg = new Message();
            msg.obj = dateToDao(data);
            msg.what = MINEFROM;
            msg.arg1 = chatMsgFieldName.FROM;
            mHandler.sendMessage(msg);
        }
    }
    //将发来的消息格式化
    private ChatMsgDao dateToDao(String data) {
        ChatMsgDao msgDao = new ChatMsgDao();
        GetGroupChatMsgDao dao = gson.fromJson(data, GetGroupChatMsgDao.class);
        msgDao.setAvater(dao.data.avatar);
        msgDao.setChatContent(dao.data.content);
        msgDao.setMsgType(MsgType(dao.data.content));
        msgDao.setReadOrUnRead(chatMsgFieldName.READ);
        msgDao.setGROUPAVATAR(dao.data.groupavatar);
        msgDao.setGROUPNAME(dao.data.groupname);
        msgDao.setSendOrfrom(chatMsgFieldName.FROM);
        msgDao.setTempTime(System.currentTimeMillis());
        msgDao.setUserName(dao.data.name);
        return msgDao;
    }

    //判断消息类型
    private int MsgType(String content) {
        String[] split = content.split("\\[");
        switch (split[0]) {
            case "img":
                return chatMsgFieldName.IMAGE;
            case "essay":
                return chatMsgFieldName.ESSAY;
            case "voice":
                return chatMsgFieldName.VOICE;
            case "video":
                return chatMsgFieldName.VIDEO;
            case "file":
                return chatMsgFieldName.FILE;
            default:
                return chatMsgFieldName.CONTENT;
        }
    }

    private CharSequence solveData(String msg) {
        for (int i = 0; i < enjoyCs.mEnjoyList.length; i++) {
            msg = msg.replace("face" + enjoyCs.mEnjoyList[i], enjoyCs.mEnjoyList[i]);
        }
        return util.replace(msg);
    }

    public void OpenChooseImage() {
        Intent albumIntent = new Intent(Intent.ACTION_PICK, null);
        albumIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        startActivityForResult(albumIntent, constant.REQUEST_ALBUM_OK);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (permissions[0].equals(Manifest.permission.WRITE_EXTERNAL_STORAGE) && grantResults[0] == 0) {

        } else if (permissions[0].equals(Manifest.permission.CAMERA) && grantResults[0] == 0) {
            takePhoto();
        } else if (permissions[0].equals(Manifest.permission.RECORD_AUDIO) && grantResults[0] == 0) {

        } else {

        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        String path = null;
        switch (requestCode) {
            /**相册获取的数据*/
            case constant.REQUEST_ALBUM_OK:
                if (resultCode == RESULT_OK) {
                    setPictureData(data);
                }
                break;
            /**相机获取的数据*/
            case constant.CROP_PHOTO:
                if (resultCode == RESULT_OK) {
                    setCameraData();
                }
                break;
        }
    }

    /**
     * 设置相机的图片
     */
    private void setCameraData() {
        String path;
        bottom_item.setVisibility(View.GONE);
        path = imageUri.getPath().replace("external_files", "");
        setSendImage(path);
    }

    /**
     * 设置相册的图片
     */
    private void setPictureData(Intent data) {
        String path;
        bottom_item.setVisibility(View.GONE);
        Uri uri = data.getData();
        path = getPath(uri);
        if (path != null) {
            setSendImage(path);
        }
    }

    /*** 发送本地图片*/
    public void setSendImage(String path) {
        ChatMsgImage imageMsg = new ChatMsgImage(this, path, this,false);
        imageMsg.setHeader_portrait(mineAvatar);
        long time = System.currentTimeMillis();
        imageMsg.setTime(time, ChatTime);
        ChatTime = time;
        msgLv.addView(imageMsg);
        scrollToBottom();
    }

    /*** 发送本地录音*/
    public void setSendAudio(String path, long voiceTime) {
        ChatVocieMsgItem rightMsgItem = new ChatVocieMsgItem(this, path, this, voiceTime,false);
        rightMsgItem.setAvater(mineAvatar);
        long time = System.currentTimeMillis();
        rightMsgItem.setTime(time, ChatTime);
        ChatTime = time;
        msgLv.addView(rightMsgItem);
        scrollToBottom();
    }

    /*** 获取相册图片的真实地址*/
    public String getPath(Uri uri) {
        String path = null;
        String[] proj = {MediaStore.Images.Media.DATA};
        ContentResolver cr = this.getContentResolver();
        Cursor cursor = cr.query(uri, proj, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        //最后根据索引值获取图片路径
        path = cursor.getString(column_index);
        return path;
    }

    /*** 解析上传地址*/
    public void pushFileData(String result, String type, long recordTime) {
        ImageUploadResultDao imageUploadResultDao = gson.fromJson(result, ImageUploadResultDao.class);
        ImageUploadResultDao.ImageUploadResult data = imageUploadResultDao.data;
        String content = type + "[" + data.url + "]";
        /**录音*/
        if (recordTime > 0) {
            content = type + "[" + data.url + "|" + recordTime + "]";
            addInfo(content, chatMsgFieldName.VOICE);
            return;
        }
        /**消息類型1图片*/
        addInfo(content, chatMsgFieldName.IMAGE);
    }

    @Override
    public void onBackPressed() {
        //聊天未读数据清空
        if (bottom_item.getVisibility() == View.VISIBLE && quite.getVisibility() != View.VISIBLE) {
            bottom_item.setVisibility(View.GONE);
        } else if (quite.getVisibility() == View.VISIBLE) {
            quite.setVisibility(View.GONE);
        } else {
            MediaPlayUtils.getInstance().stop();
            ChatRecordSPUtils.setRecordString(this, kefuId, kefuId + "_count", "0");
            finish();
        }
    }

    //打开相机
    public void takePhoto() {
        File file;
        file = new File(Environment.getExternalStorageDirectory(), "picture");
        if (!file.exists()) {
            file.mkdir();
        }
        output = new File(file, System.currentTimeMillis() + ".jpg");
        try {
            if (output.exists()) {
                output.delete();
            }
            output.createNewFile();
        } catch (Exception e) {
            e.printStackTrace();
        }
        imageUri = FileProvider.getUriForFile(this, getPackageName() + ".provider", output);
        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        startActivityForResult(intent, constant.CROP_PHOTO);
    }
}

